import torch
from torch import nn
import torch.nn.functional as F
import torchvision.transforms as T
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

device = "gpu" if torch.cuda.is_available() else "cpu"


class ResidualBlock(nn.Module):
    def __init__(self, inchannel, outchannel, stride=1):
        super(ResidualBlock, self).__init__()
        self.left = nn.Sequential(
            nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(outchannel),
            nn.ReLU(inplace=True),
            nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(outchannel)
        )
        self.shortcut = nn.Sequential()
        if stride != 1 or inchannel != outchannel:
            self.shortcut = nn.Sequential(
                nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(outchannel)
            )

    def forward(self, x):
        out = self.left(x)
        out += self.shortcut(x)
        out = F.relu(out)
        return out


class ResNet(nn.Module):
    def __init__(self, ResidualBlock, num_classes=10):
        super(ResNet, self).__init__()
        self.inchannel = 64
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(),
        )
        self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=1)
        self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2)
        self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2)
        self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2)
        self.fc = nn.Linear(512, num_classes)

    def make_layer(self, block, channels, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)  # strides=[1,1]
        layers = []
        for stride in strides:
            layers.append(block(self.inchannel, channels, stride))
            self.inchannel = channels
        return nn.Sequential(*layers)

    def forward(self, x):
        out = self.conv1(x)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = F.avg_pool2d(out, 4)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out


def resnet18():
    return ResNet(ResidualBlock)


if __name__ == '__main__':
    cifar = torchvision.datasets.CIFAR10(train=True, root=r'F:\cifar', transform=T.ToTensor(), download=True)
    dataloader = DataLoader(cifar, batch_size=512)
    cifar_test = torchvision.datasets.CIFAR10(train=False, root=r'F:\cifar', transform=T.ToTensor(), download=True)
    dataloader_test = DataLoader(cifar_test, batch_size=512)
    model = resnet18()
    optimizer = torch.optim.Adam(lr=0.01, params=model.parameters())
    loss_fn = nn.CrossEntropyLoss()
    log = SummaryWriter(log_dir="./runs")
    EPOCHS = 50
    step = 1
    for epoch in range(1, EPOCHS + 1):
        model.train()
        for (im, target) in dataloader:
            im = im.to(device)
            target = target.long().to(device)
            out = model(im).to(device)
            loss = loss_fn(out, target)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            with torch.no_grad():
                log.add_scalar("Loss", float(loss), step)
                step += 1
        model.eval()
        with torch.no_grad():
            right = 0
            for (im, target) in dataloader_test:
                out = model(im)
                right += (torch.sum(torch.argmax(out, dim=1) == target))
            acc = right / len(cifar_test)
            log.add_scalar("Accuracy", acc, epoch)
